package com.wellsantos.dgwt.client.view;

import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.dgwt.client.dijit.layout.LayoutWidget;
import com.googlecode.dgwt.client.dijit.layout.VFlexPanel;

public class ViewHandler {

	private static MainViewBase mainView = null;
	private static ViewBase currentView = null;
	private static VFlexPanel centerPanel = new VFlexPanel();	

	
	protected ViewHandler() {
	}
	

	protected void setMainView(MainViewBase view){
		assert (view != null) : "MainView can't be NULL";
		mainView = view;
	}

	
	public MainViewBase getMainView(){
		assert (mainView != null) : "MainView was not defined";
		return mainView;
	}

	
	public static ViewBase getCurrentView() {
		return currentView;
	}


	public void showView(ViewBase view) {
		
		if (view instanceof MainViewBase){
			
			if (currentView != null){
				currentView.onHide();
				currentView = null;
			}
			
			if (mainView != null){
				mainView.onHide();
				RootPanel.get().remove(mainView.getWidget());
			}
			
			setMainView((MainViewBase) view);
			RootPanel.get().add(mainView.getWidget());
			Document.get().setTitle(mainView.getTitle());
			mainView.onShow();
			
		} else {
			if (currentView != null){
				currentView.onHide();
			}
			
			currentView = view;
			showCurrentView();
		}
	}
	
	
	private void showCurrentView(){
		if (currentView != null){
			currentView.onShow();
			Widget widget = currentView.getWidget();
			
			if (currentView.isBetterCentered()){
				widget = wrapCenter(widget);
			}
			
			getMainView().setContent(widget, currentView.getTitle());		
		} else {
			getMainView().setContent(wrapCenter(null), "");
		}
	}

	
	private static LayoutWidget wrapCenter(Widget widget){
		centerPanel.clear();
		if (widget != null){
			centerPanel.add(widget);
			centerPanel.setWidth("100%");
			centerPanel.setCellHorizontalAlignment(widget, HasHorizontalAlignment.ALIGN_CENTER);
		}
		return centerPanel;
	}


}
